import { useState, useEffect, useContext } from "react";
import { NavBar, List, InfiniteScroll, Badge, SearchBar } from "antd-mobile";
import { UserAddOutlined, UserOutlined, UsergroupAddOutlined, ProjectFilled } from '@ant-design/icons'
import { useHistory } from 'react-router-dom';

import AvatarImage from "../../../components/AvatarImage";
import { MySdkStoreContext } from '../../../context';
import { NEW_APPLICATION_STORAGE_KEY } from '../../../constants';

import "./style.scss";

export default function(props) {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const { hasNewFriend, hasNewGroupMember } = props;
  const [pagination, setPagination] = useState({ pageIndex: 1, totalPage: 1, totalItmeCount: 0 });
  const [list, setList] = useState([]);
  const [unReadNewGroupMemberApplication, setUnReadNewGroupMemberApplication] = useState(0);
  const [unReadNewFriendApplication, setUnReadNewFriendApplication] = useState(0);

  useEffect(() => {
    if (hasNewFriend) {
      setUnReadNewFriendApplication(number => number + 1);
    }
  }, [hasNewFriend]);

  useEffect(() => {
    if (hasNewGroupMember) {
      setUnReadNewGroupMemberApplication(number => number + 1);
    }
  }, [hasNewGroupMember]);

  const getMailList = (pageIndex: number) => {
    mySdkStore.sdk.queryCommonlyUsedContact({ pageIndex }).then(({ next, rows, totalItmeCount, totalPage }) => {
      setPagination({ pageIndex: +next, totalItmeCount, totalPage });
      setList(rows);
    });
  }

  const getNextData = async () => {
    await getMailList(pagination.pageIndex + 1);
  }

  useEffect(() => {
    getMailList(1);
  }, []);

  useEffect(async () => {
    // 在本地存储中读取新申请的“已读/未读”状态，如果未读拉取未处理的申请数量进行展示
    const hasReadNewApplicationStr = localStorage.getItem(NEW_APPLICATION_STORAGE_KEY)??'{}';
    try {
      const hasReadNewApplicationObj = JSON.parse(hasReadNewApplicationStr);
      if (!hasReadNewApplicationObj.hasReadNewFriendApplication) {
        const { totalItemCount: count1 } = await mySdkStore.sdk.queryFriendApplyListByStatus({ pageIndex: 1, status: '2', pageSize: 100 });
        setUnReadNewFriendApplication(unReadNewFriendApplication => unReadNewFriendApplication + +count1);
      }
      if (!hasReadNewApplicationObj.hasReadNewGroupMemberApplication) {
        const { totalItemCount: count2 } = await mySdkStore.sdk.queryGroupJoinApplyList({ pageIndex: 1, status: '2', pageSize: 100 });
        setUnReadNewGroupMemberApplication(unReadNewGroupMemberApplication => unReadNewGroupMemberApplication + +count2);
      }
    } catch {
    }
  }, []);

  return (<div className="mailListPage">
      <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>通讯录</NavBar>
      <SearchBar style={{ '--background': '#ffffff', margin: 12 }} placeholder="搜索" onFocus={() => history.push({ pathname: '/globalSearch'})} />
      <div className="scrollWrap">
      <div className="operationBarWrap">
        <div className="operationBar" onClick={() => history.push({ pathname: '/joinGroupApplyList' })}>
          <div className="operationIcon" style={{ background: 'rgba(253,127,44,1)'}}>
            <UsergroupAddOutlined style={{ color: '#fff' }}  />
          </div>
          入群申请
          { !!unReadNewGroupMemberApplication &&
            <div style={{ flex: 1 }}>
              <Badge style={{ float: 'right' }} content={unReadNewGroupMemberApplication} />
            </div>
          }
        </div>
        <div className="operationBar" onClick={() => history.push({ pathname: '/newFriendList' })}>
          <div className="operationIcon" style={{ background: 'rgba(253,127,44,1)'}}>
            <UserAddOutlined style={{ color: '#fff' }} />
          </div>
          新的朋友
          { !!unReadNewFriendApplication &&
            <div style={{ flex: 1 }}>
              <Badge content={unReadNewFriendApplication} />
            </div>
          }
        </div>
        <div className="operationBar" onClick={() => history.push({ pathname: '/friendList' })}>
          <div className="operationIcon">
            <UserOutlined style={{ color: '#fff' }}  />
          </div>
          我的好友
        </div>
        <div className="operationBar" onClick={() => history.push({ pathname: '/groupList' })}>
          <div className="operationIcon">
            <UsergroupAddOutlined style={{ color: '#fff' }}  />
          </div>
          我的群组
        </div>
        <div className="operationBar" onClick={() => history.push({ pathname: '/contactorList' })}>
          <div className="operationIcon">
            <ProjectFilled style={{ color: '#fff' }}  />
          </div>
          全部联系人
        </div>
      </div>
      <div className="sectionTitle">常用联系人</div>
      <List>
        {list.map(item => {
          return <List.Item
              key={item.userId}
              prefix={<AvatarImage
              src={item.avatarUrl}
              style={{ borderRadius: 8 }}
              fit='cover'
              width={42}
              height={42}
              nickName={item.nickName}
              userName={item.userName}
              userId={item.userId}
              onClick={() => history.push({ pathname: `/userInfo/${item.userId}` })}
            />}
            description={<>ID: {item.userId}</>}
          ><span onClick={() => history.push({ pathname: `/userInfo/${item.userId}` })}>{item.userName}</span></List.Item>
        })}
        <InfiniteScroll loadMore={getNextData} hasMore={pagination.totalItmeCount > list.length} />
      </List>
      </div>
  </div>
  )
}